<template>
  <div class="sensor-charts">
    <div class="chart-container">
      <div class="chart-title">温湿度变化趋势</div>
      <div ref="tempHumidityChart" class="chart"></div>
    </div>
    <div class="chart-container">
      <div class="chart-title">氮磷钾含量变化</div>
      <div ref="npkChart" class="chart"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import * as echarts from 'echarts'
import { 
  getSensorHistory
} from '../api/sensor'
import dayjs from 'dayjs'

const tempHumidityChart = ref(null)
const npkChart = ref(null)
let tempHumidityInstance = null
let npkInstance = null

// 初始化温湿度图表
const initTempHumidityChart = (data) => {
  if (!tempHumidityChart.value) {
    console.warn('Temperature-humidity chart container not found');
    return;
  }

  // 等待 DOM 渲染完成
  nextTick(() => {
    if (tempHumidityChart.value.clientWidth === 0 || tempHumidityChart.value.clientHeight === 0) {
      console.warn('Invalid temperature-humidity chart dimensions');
      setTimeout(() => initTempHumidityChart(data), 100); // 延迟重试
      return;
    }

    tempHumidityInstance = echarts.init(tempHumidityChart.value)
    const times = data.times
    const temperatures = data.temperatures
    const humidity = data.humidity
    
    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross'
        },
        formatter: function(params) {
          return params.map(param => {
            return `${param.seriesName}: ${param.value}${param.seriesName === '温度' ? '℃' : '%'}`
          }).join('<br/>')
        }
      },
      legend: {
        data: ['温度', '湿度'],
        textStyle: {
          color: '#fff'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: times,
        axisLabel: {
          color: 'rgba(255, 255, 255, 0.65)'
        }
      },
      yAxis: [
        {
          type: 'value',
          name: '温度(℃)',
          nameTextStyle: {
            color: 'rgba(255, 255, 255, 0.65)'
          },
          axisLabel: {
            color: 'rgba(255, 255, 255, 0.65)'
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(255, 255, 255, 0.1)'
            }
          }
        },
        {
          type: 'value',
          name: '湿度(%)',
          nameTextStyle: {
            color: 'rgba(255, 255, 255, 0.65)'
          },
          axisLabel: {
            color: 'rgba(255, 255, 255, 0.65)'
          },
          splitLine: {
            show: false
          }
        }
      ],
      series: [
        {
          name: '温度',
          type: 'line',
          smooth: true,
          data: temperatures,
          itemStyle: {
            color: '#ff7875'
          }
        },
        {
          name: '湿度',
          type: 'line',
          smooth: true,
          yAxisIndex: 1,
          data: humidity,
          itemStyle: {
            color: '#69c0ff'
          }
        }
      ]
    }
    
    tempHumidityInstance.setOption(option)
  })
}

// 初始化氮磷钾图表
const initNPKChart = (data) => {
  if (!npkChart.value) {
    console.warn('NPK chart container not found');
    return;
  }

  // 等待 DOM 渲染完成
  nextTick(() => {
    if (npkChart.value.clientWidth === 0 || npkChart.value.clientHeight === 0) {
      console.warn('Invalid NPK chart dimensions');
      setTimeout(() => initNPKChart(data), 100); // 延迟重试
      return;
    }

    npkInstance = echarts.init(npkChart.value)
    const times = data.times
    const nitrogen = data.nitrogen
    const phosphorus = data.phosphorus
    const potassium = data.potassium
    
    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        },
        formatter: function(params) {
          return params.map(param => {
            return `${param.seriesName}: ${param.value} mg/kg`
          }).join('<br/>')
        }
      },
      legend: {
        data: ['氮', '磷', '钾'],
        textStyle: {
          color: '#fff'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: times,
        axisLabel: {
          color: 'rgba(255, 255, 255, 0.65)'
        }
      },
      yAxis: {
        type: 'value',
        name: 'mg/kg',
        nameTextStyle: {
          color: 'rgba(255, 255, 255, 0.65)'
        },
        axisLabel: {
          color: 'rgba(255, 255, 255, 0.65)'
        },
        splitLine: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.1)'
          }
        }
      },
      series: [
        {
          name: '氮',
          type: 'bar',
          data: nitrogen,
          itemStyle: {
            color: '#95de64'
          }
        },
        {
          name: '磷',
          type: 'bar',
          data: phosphorus,
          itemStyle: {
            color: '#ffc53d'
          }
        },
        {
          name: '钾',
          type: 'bar',
          data: potassium,
          itemStyle: {
            color: '#40a9ff'
          }
        }
      ]
    }
    
    npkInstance.setOption(option)
  })
}

// 获取历史数据
const fetchHistoryData = async () => {
  try {
    const endTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
    const startTime = dayjs().subtract(6, 'hour').format('YYYY-MM-DD HH:mm:ss')
    
    // 分别获取各种传感器的历史数据
    const [tempData, moistureData, nitrogenData, phosphorusData, potassiumData] = await Promise.all([
      getSensorHistory('temperature', { startTime, endTime }),
      getSensorHistory('moisture', { startTime, endTime }),
      getSensorHistory('nitrogen', { startTime, endTime }),
      getSensorHistory('phosphorus', { startTime, endTime }),
      getSensorHistory('potassium', { startTime, endTime })
    ])
    
    // 处理数据
    const times = tempData.map(item => dayjs(item.timestamp).format('HH:mm'))
    const temperatures = tempData.map(item => Number(item.value))
    const humidity = moistureData.map(item => Number(item.value))
    const nitrogen = nitrogenData.map(item => Number(item.value))
    const phosphorus = phosphorusData.map(item => Number(item.value))
    const potassium = potassiumData.map(item => Number(item.value))
    
    // 初始化图表
    initTempHumidityChart({ times, temperatures, humidity })
    initNPKChart({ times, nitrogen, phosphorus, potassium })
    
    // 设置定时刷新
    setTimeout(fetchHistoryData, 300000) // 每5分钟刷新一次
  } catch (error) {
    console.error('获取历史数据失败:', error)
    console.log('Error details:', error.message)
    setTimeout(fetchHistoryData, 60000) // 出错后1分钟重试
  }
}

// 处理窗口大小变化
const handleResize = () => {
  tempHumidityInstance?.resize()
  npkInstance?.resize()
}

onMounted(() => {
  nextTick(() => {
    fetchHistoryData()
    window.addEventListener('resize', handleResize)
  })
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  tempHumidityInstance?.dispose()
  npkInstance?.dispose()
})
</script>

<style scoped>
.sensor-charts {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding: 10px;
  height: 100%;
  background: rgba(0, 0, 0, 0.2);
  border-radius: 8px;
}

.chart-container {
  flex: 1;
  background: rgba(0, 0, 0, 0.2);
  border-radius: 8px;
  padding: 15px;
  min-height: 200px;
}

.chart-title {
  font-size: 16px;
  color: #1890ff;
  margin-bottom: 10px;
  font-weight: 500;
}

.chart {
  width: 100%;
  height: calc(100% - 30px);
  min-height: 150px;
}
</style> 